
import { createOrUpdateApi4USetting, fetchList } from '@/views/coding/a3UserSetting/api' // UserSetting

String.prototype.replaceAll = function(s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
}

export default {
    // save to remote server
    saveRemote(key, value) {
        const data = {}
        data.name = key
        data.value = JSON.stringify(value).replaceAll("\"","\\\"")
        createOrUpdateApi4USetting(data).then( result => {
            console.log(result)
        })
    },
    // load all user setting after login
    loadByUserId(userId) {
        const query = {page: 1, limit: 200000, createmanId: userId}
        return fetchList(query).then( result => {
            const list = result.map.rows
            list.forEach( item => {
                const name = item.name;
                const value = item.value;
                if (value === 'true' || value === 'false' || !isNaN(value)) {
                    this.saveBool(name, value)
                }
                else{
                    const value1 = value.replaceAll("\\\\\"", "\"")
                    window.localStorage.setItem(name, value1)
                }
            })
        })
    },

    saveArr(key, arr, isRemote) {
        window.localStorage.setItem(key, JSON.stringify(arr))
        if (isRemote) {
            this.saveRemote(key, arr)
        }
    },
    readArr(key) {
        return JSON.parse(window.localStorage.getItem(key) || '[]')
    },

    saveObj(key, obj, isRemote) {
        window.localStorage.setItem(key, JSON.stringify(obj))
      if (isRemote) {
        this.saveRemote(key, obj)
      }
    },
    readObj(key) {
        return JSON.parse(window.localStorage.getItem(key) || '{}')
    },

    saveStr(key, str, isRemote) {
        window.localStorage.setItem(key, str)
      if (isRemote) {
        this.saveRemote(key, str)
      }
    },
    readStr(key) {
        return JSON.parse(window.localStorage.getItem(key) || '')
    },

    // 基本数据类型 bool, number 都用这个
    saveBool(key, b, isRemote) {
       window.localStorage.setItem(key, b)
        if (isRemote) {
          this.saveRemote(key, b)
        }
    },
    readBool(key) {
        return JSON.parse(window.localStorage.getItem(key) || false)
    },

    /**
     * 从local storage中，读取列表头宽度，undefined则返回默认值
     * @param prop
     * @param defaultValue
     * @returns {*}
     */
    getColumnWidthFromStorage(prop, defaultValue, ColumnShowListWidthKey) {
        const columnWidthJson = this.readObj(ColumnShowListWidthKey)
        let width = columnWidthJson[prop]
        if (width === undefined) {
          width = defaultValue
        }
        return width
    }

}
